package com.crm.jdy.common.shiro;

import com.crm.jdy.common.dto.RoleInfoDto;
import com.crm.jdy.common.pojo.PermissionInfo;
import com.crm.jdy.common.utils.MD5Utils;
import com.crm.jdy.service.usermanager.UserInfoService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.util.StringUtils;

import java.util.Iterator;
import java.util.List;

public class MyRealm extends AuthorizingRealm {

    @Reference(version = "${service.version}", check = false)
    UserInfoService userInfoService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("============用户授权==============");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        /*获取当前的用户,已经登录后可以使用在任意的地方获取用户的信息*/
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        /*查询用户的权限*/
        RoleInfoDto role = userInfoService.getRoleInfo(username);
        /*将role放在一个集合中,多个权限使用集合*/
//        info.addRole(role.getInfoSet());
//        给用户增加角色
        info.addRole(role.getRoleName());
//        给用户增加权限
        if(null !=role && StringUtils.isEmpty(role)){
            Iterator<PermissionInfo> iterator = role.getInfoSet().iterator();
            while (iterator.hasNext()) {
                info.addStringPermission(iterator.next().getPerName());
            }
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("============用户验证==============");
        //从token中获取信息,此token只是shiro用于身份验证的,并非前端传过来的token.
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        System.out.println(token);
        String username = token.getUsername();
        String password = userInfoService.getPassword(username);
        if (null == password){
            throw new AuthenticationException("doGetAuthenticationInfo中的用户名不对");
        } else if (!password.equals( new String(token.getPassword()))){
            throw new AuthenticationException("doGetAuthenticationInfo中的密码不对");
        }
        //组合一个验证信息
        System.out.println("token.getPrincipal()默认返回的username======"+token.getPrincipal());
        System.out.println("getName()"+getName());
        SimpleAuthenticationInfo info =
                new SimpleAuthenticationInfo(token.getPrincipal(),password,getName());
        return info;
    }

}
